import os
import uuid
from datetime import timedelta
from flask import Flask, request, jsonify, send_from_directory
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime

app = Flask(__name__)

# 配置
UPLOAD_FOLDER = 'images'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
SERVER_URL = 'XXXXXXXXXXXXXXXXXXXX'         # 服务器地址,形如"http://127.0.0.1:5000"
UPLOAD_PASSWORD = "XXXXXXXXXXXXXXXXXXXX"    # 设置你的上传密码
PORT = 5000                                 # 开放端口号
DEBUG = False

# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def clear_image_folder():
    """清空图片文件夹"""
    for filename in os.listdir(UPLOAD_FOLDER):
        file_path = os.path.join(UPLOAD_FOLDER, filename)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print(f"删除文件失败 {file_path}: {e}")
    print("图片文件夹已清空")

# 配置定时任务
scheduler = BackgroundScheduler()
scheduler.add_job(
    func=clear_image_folder,
    trigger='interval',
    minutes=10,
    next_run_time=datetime.now() + timedelta(minutes=10)
)
scheduler.start()

@app.route('/upload', methods=['POST'])
def upload_image():
    """图片上传接口（需要密码验证）"""
    # 验证密码
    password = request.form.get('password')
    if password != UPLOAD_PASSWORD:
        return jsonify({'error': '无效的密码'}), 401
    
    if 'file' not in request.files:
        return jsonify({'error': '未找到文件部分'}), 400
    
    file = request.files['file']
    
    if file.filename == '':
        return jsonify({'error': '未选择文件'}), 400
    
    if file and allowed_file(file.filename):
        # 生成唯一文件名
        ext = file.filename.rsplit('.', 1)[1].lower()
        filename = f"{uuid.uuid4().hex}.{ext}"
        file_path = os.path.join(UPLOAD_FOLDER, filename)
        
        # 保存文件
        file.save(file_path)
        
        # 修改URL拼接方式
        image_url = f"{SERVER_URL}/images/{filename}"  # 改为匹配下面的serve_image路由
        return jsonify({'url': image_url}), 200
    
    return jsonify({'error': '不允许的文件类型'}), 400

@app.route('/images/<filename>')
def serve_image(filename):
    """提供图片访问服务"""
    return send_from_directory(UPLOAD_FOLDER, filename)

if __name__ == '__main__':
    try:
        app.run(host='0.0.0.0', port=PORT, debug=DEBUG)
    finally:
        scheduler.shutdown()